<template>
  <section class="todoapp">
    <TodoHeader @addTask="hAdd" />
    <TodoMain @changeH="hChange" @getId="hDelt" :list="shuwList" />
    <TodoFooter
      @changeType="hChangeType"
      @delDone="hDelDone"
      :list="shuwList"
    />
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
export default {
  // 局部注册组件
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 1, name: "吃饭", isDone: true },
      //   { id: 2, name: "睡觉", isDone: false },
      //   { id: 3, name: "打豆豆", isDone: true },
      // ],
      list: JSON.parse(localStorage.getItem("list") || "[]"),
      type: "all",
    };
  },
  methods: {
    hDelt(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    hChange(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.isDone = !obj.isDone;
    },
    hAdd(takname) {
      this.list.push({
        name: takname,
        id: Date.now(),
        isDone: false,
      });
    },
    hDelDone() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    hChangeType(type) {
      this.type = type;
    },
  },
  computed: {
    // 根据传递过来的type 来决定返回什么数组
    shuwList() {
      if (this.type === "all") {
        return this.list;
      } else if (this.type === "active") {
        return this.list.filter((item) => !item.isDone);
      } else if (this.type === "completed") {
        return this.list.filter((item) => item.isDone);
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("list", JSON.stringify(this.list));
      },
    },
  },
};
</script>

<style scoped>
</style>